package com.dayaokeji.rhythmschoolstudent.client.mine.account

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.support.v4.app.ActivityCompat
import android.text.TextUtils
import android.view.View
import com.dayaokeji.rhythmschoolstudent.R
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager
import com.dayaokeji.rhythmschoolstudent.client.common.base.ActivityTemplateMethod
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity
import com.dayaokeji.rhythmschoolstudent.event.ResetMobileEvent
import com.dayaokeji.rhythmschoolstudent.utils.InputUtils
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils
import com.dayaokeji.server_api.ApiUtils
import com.dayaokeji.server_api.ServerResponse
import com.dayaokeji.server_api.api.SmsApi
import com.dayaokeji.server_api.api.UserApi
import com.dayaokeji.server_api.domain.SendSmsType
import com.dayaokeji.server_api.domain.Sms
import com.dayaokeji.server_api.domain.UpdateMobie
import com.dayaokeji.server_api.domain.UserInfo
import kotlinx.android.synthetic.main.activity_reset_mobile.*
import org.greenrobot.eventbus.EventBus
import retrofit2.Call

/**
 * 重置手机号码
 */
class ResetMobileActivity : BaseActivity(){

    companion object {
        fun navigation(cxt: Context) {
            val intent = Intent(cxt, ResetMobileActivity::class.java)
            ActivityCompat.startActivity(cxt,intent,null)
        }
    }

    private val smsApi by lazy { ApiUtils.getApi(SmsApi::class.java) }
    private val userApi by lazy { ApiUtils.getApi(UserApi::class.java) }
    private var sendSmsCall: Call<ServerResponse<Void>>? = null
    private var validateSmsCall: Call<ServerResponse<Boolean>>? = null
    private var updateMobileCall: Call<ServerResponse<UserInfo>>? = null

    private var mobileStr: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_reset_mobile)
        toolbar?.let {
            setSupportActionBar(it)
        }
    }

    /**
     * 发送验证码
     */
    fun sendVerifyCode(view: View) {
        if (InputUtils.validateInput(etMobile, "请输入手机号码")) {
            val mobile = etMobile.text.toString().replace(" ","").trim()
            if (mobile.length == 11 && TextUtils.isDigitsOnly(mobile)) {
                mobileStr = mobile
                val sendSms = Sms()
                sendSms.phone = mobile
                sendSms.type = SendSmsType.UPDATE.type
                sendSmsCall = smsApi.send(sendSms)
                sendSmsCall?.enqueue(object : ServerCallback<Void>(this, "正在发送短信验证码...") {
                    override fun onResponse(success: Boolean, response: ServerResponse<Void>) {
                        if (success) {
                            countDownTimer.start()
                            ToastUtils.success("已向您的手机发送验证码")
                        } else {
                            ToastUtils.warning("发送验证码失败")
                            countDownTimer.onFinish()
                        }
                    }

                    override fun onFailure(call: Call<ServerResponse<Void>>, t: Throwable) {
                        super.onFailure(call, t)
                        ToastUtils.warning("发送验证码失败")
                        countDownTimer.onFinish()
                    }
                })
            } else {
                ToastUtils.warning("请输入11位手机号码")
            }

        }
    }

    /**
     * 验证验证码
     */
    fun checkVerifyCode(view: View) {
        if (InputUtils.validateInput(etVerifyCode, "请输入验证码")) {
            val verifyCode = etVerifyCode.text.toString().trim()
            val sms = Sms()
            sms.phone = mobileStr
            sms.type = SendSmsType.UPDATE.type
            sms.code = verifyCode
            validateSmsCall = smsApi.validate(sms)
            validateSmsCall?.enqueue(object : ServerCallback<Boolean>(this, "正在验证...") {
                override fun onResponse(success: Boolean, response: ServerResponse<Boolean>) {
                    if (success) {
                        if (response.body != null && response.body) {
                            updateMobile()
                        } else {
                            ToastUtils.warning("验证码失效")
                            countDownTimer.onFinish()
                        }
                    }
                }

                override fun onFailure(call: Call<ServerResponse<Boolean>>, t: Throwable) {
                    super.onFailure(call, t)
                    ToastUtils.warning("验证码失效")
                    countDownTimer.onFinish()
                }
            })
        }
    }

    /**
     * 更新手机号码
     */
    private fun updateMobile() {
        val userInfo = UserUtils.getUserInfo()
        userInfo?.let {
            updateMobileCall = userApi.updatePhone(UpdateMobie(it.id,mobileStr))
            updateMobileCall?.enqueue(object :ServerCallback<UserInfo>(){
                override fun onResponse(success: Boolean, response: ServerResponse<UserInfo>?) {
                    if (success) {
                        ToastUtils.info("更新成功")
                        EventBus.getDefault().post(ResetMobileEvent(mobileStr))
                        ActivityStackManager.finish()
                    }
                }
            })
        }
    }

    private val countDownTimer = object : CountDownTimer((60 * 1000).toLong(), 1000) {
        @SuppressLint("SetTextI18n")
        override fun onTick(millisUntilFinished: Long) {
            if (btnSendVerifyCode != null) {
                btnSendVerifyCode.isEnabled = false
                btnSendVerifyCode.text = "已发送（ " + millisUntilFinished / 1000 + " s）"
            }
        }

        override fun onFinish() {
            if (btnSendVerifyCode != null) {
                this.cancel()
                btnSendVerifyCode.text = "重新获取验证码"
                btnSendVerifyCode.isEnabled = true
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        sendSmsCall?.cancel()
        validateSmsCall?.cancel()
        updateMobileCall?.cancel()
    }
}
